import {useState} from "react";

interface State<D>{
    error: Error | null;
    data: D | null;
    status: 'idle' | 'loading' | 'error' | 'success'
}

const defaultInitialState:State<null> = {
    status : 'idle',
    data : null,
    error : null
}

export const useAsync = <D>(initialState ?: State<D>) =>{
    const [state, setState] = useState<State<D>>({
        ...defaultInitialState,
        ...initialState
    })

    const setData = (data:D) => setState({
        data,
        status: 'success',
        error: null
    })

    const setError = (error:Error) => setState({
        error,
        status: 'error',
        data: null
    })

    //run用来触发异步请求
    const run = (promises: Promise<D>) => {
        if(!promises || !promises.then){
            throw new Error('请传入Promise类型数据')
        }
        setState({...state, status: 'loading'})
        return promises.then(data => {
            setData(data)
            return data
        }).catch(error => {
            setError(error)
            return Promise.reject(error)
        })
    }

   return {
        isIdle: state.status === 'idle',
       isLoading: state.status ==='loading',
       isError: state.status === 'error',
       isSuccess: state.status === 'success',
       run,
       setData,
       setError,
       ...state

   }
}